//
//  WeiboTableViewController.m
//  微博
//
//  Created by situ_ios_004 on 15/10/23.
//  Copyright © 2015年 situ_ios_004. All rights reserved.
//

#import "WeiboTableViewController.h"
#import "Status.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#import "StatusTableViewCell.h"
#import "WebImage/WebImage.h"

@interface WeiboTableViewController ()
{
    NSMutableArray<Status*> * _statues;
    
    
    UIImage * _defaultAvatar;
}
@end

@implementation WeiboTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    NSString* ipaddr=[self getIPAddress];
    
    self->_defaultAvatar = [UIImage imageNamed:@"7.jpg"];
    
    [self sendRequest];

}
- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}

#pragma mark 发送数据请求
-(void)sendRequest{
    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.0.105:8080/statuses"];
    //注意对于url中的中文是无法解析的，需要进行url编码(指定编码类型位utf-8)
    //另外注意url解码使用stringByRemovingPercentEncoding方法
    urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建url链接
    NSURL *url=[NSURL URLWithString:urlStr];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //3.创建会话（这里使用了一个全局会话）并且启动任务
    NSURLSession *session=[NSURLSession sharedSession];

    //从会话创建任务
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            dispatch_async(dispatch_get_main_queue(),^{
                [self loadData:data];
            });
            
            NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",dataStr);
            
        }else{
            NSLog(@"error is :%@",error.localizedDescription);
        }
    }];
    
    [dataTask resume];//恢复线程，启动任务
}
-(void)loadData:(NSData *)data{
    self->_statues =[[NSMutableArray alloc]init];
    
    /*json序列化
     options:序列化选项，枚举类型，但是可以指定为枚举以外的类型，例如指定为0则可以返回NSDictionary或者NSArray
     a.NSJSONReadingMutableContainers:返回NSMutableDictionary或NSMutableArray
     b.NSJSONReadingMutableLeaves：返回NSMutableString字符串
     c.NSJSONReadingAllowFragments：可以解析JSON字符串的外层既不是字典类型（NSMutableDictionary、NSDictionary）又不是数组类型（NSMutableArray、NSArray）的数据,但是必须是有效的JSON字符串
     error:错误信息
     */
    NSError *error;
    //将对象序列化为字典
    NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    NSArray *array= (NSArray *)dic[@"status"];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        Status *status=[[Status alloc]init];
        //通过KVC给对象赋值
        [status setValuesForKeysWithDictionary:obj];
        
        User *user=[[User alloc]init];
        [user setValuesForKeysWithDictionary:obj[@"user"]];
        status.user=user;
        
        [self->_statues addObject:status];
    }];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
     return self->_statues.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StatusTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"status" forIndexPath:indexPath];
    
    Status * status = [self->_statues objectAtIndex:indexPath.row];
    
    cell.name.text=status.user.name;
    cell.date.text=(NSString*)status.createAt;
    
     //cell.date.text=[NSDateFormatter localizedStringFromDate:status.createAt dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterNoStyle];
    
    cell.device.text=status.source;
    cell.content.text=status.text;
    NSString* urlStr=[status.profileImageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建url链接
    NSURL *url=[NSURL URLWithString:urlStr];
    [cell.image sd_setImageWithURL:url placeholderImage:self->_defaultAvatar];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    Status *status = self->_statues[indexPath.row];
    
    //跟据字串的内容和放置的宽度以及字体来计算字符串显示时所占的高度
    CGFloat width=[UIScreen mainScreen].bounds.size.width-16;
    CGRect rc = [status.text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]} context:nil];
    
    return 75+rc.size.height+16;
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
